package com.smartao.core.config;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * config类的父类
 * @author Ricky
 * 子类属性必须有get和set方法，子类属性需要赋初始值
 */
public class BaseConfig implements Serializable {

	private static final long serialVersionUID = 2145929250279805182L;
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	protected final String prefix;

	public BaseConfig(String prefix) {
		super();
		this.prefix = prefix;
	}

	public static String getProperty(String key) {
		HashMap<String,String> properties = ConfigHolder.getInstance().getProperties();
		return properties.get(key);
	}

	/**
	 * 加载配置项
	 */
	@SuppressWarnings("unchecked")
	public <T extends BaseConfig> T loadConfig() {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			if(Modifier.isStatic(field.getModifiers())){
				continue;
			}
			String fieldName = field.getName();
			String fieldValue = getProperty(prefix + fieldName);
			try{
				PropertyDescriptor pd = new PropertyDescriptor(fieldName, this.getClass());
				Method writeMethod = pd.getWriteMethod();
				writeMethod.invoke(this, fieldValue);
			}catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
		return (T) this;
	}
	
	public String getFieldKey(String fieldName) {
		return prefix + fieldName;
	}

}
